package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2024-08-31
 * Time: 15:08
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器！");
        while(true) {
            Socket clientSocket = serverSocket.accept();
            ExecutorService service = Executors.newCachedThreadPool();
            service.submit(() -> {
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }

            /*Thread t = new Thread(() -> {
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }*/
    }

    private void processConnection(Socket clientSocket) throws IOException {
        //1.先打印客户端信息
        System.out.printf("[%s:%d] 客户端上线！\n",clientSocket.getInetAddress(),clientSocket.getPort());

        //2.获取socket中的流对象
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true) {
                //1.读取并解析
                if(!scanner.hasNext()) {
                    break;
                }
                String request = scanner.next();
                //2.根据计算返回响应
                String response = process(request);

                //3.将信息返回客户端
                printWriter.println(response);
                printWriter.flush();

                //4.打印日志
                System.out.printf("[%s:%d] request = %s  response = %s\n",clientSocket.getInetAddress(),clientSocket.getPort(),
                request,response);

            }
        }catch(IOException e) {
            e.printStackTrace();
        }finally {
            System.out.println("客户端下线!");
            clientSocket.close();
        }

    }
    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}

